#!/usr/bin/python3
# -*- coding: utf8 -*-
# Date   : 2021/07/22
# Author : Kwan
# Email  : allenxian@live.com
# Blog   : https://my.oschina.net/u/4173440

from datetime import datetime, timedelta
from flask import json, session
from project.define import AxiosMessage
from project.modules import RecordParking, RecordEntrance, RecordExit, ChargeDetail


class Messager(AxiosMessage):
    """
    消息管理器
    """
    def __init__(self) -> None:
        super().__init__()
        self.__view_names = {"parking":"在場記錄","charge":"收費記錄"}

    def default_gatetime_range(self):
        """
        默认时间范围
        """
        now = datetime.now()
        return f"{(now - timedelta(days=7)).strftime('%Y/%m/%d %H:%M:%S')} - {now.strftime('%Y/%m/%d %H:%M:%S')}"

    def __get_data(self, view, **data):
        """
        获取数据
        """
        r = None
        if view in ("parking","past"):
            r = RecordParking.selected_data(**data)
        elif view == 'entrance':
            r = RecordEntrance.selected_data(**data)
        elif view == "exit":
            r = RecordExit.selected_data(**data)
        if r:
            return self.json_data(**r.to_dict())
        return "Fail"

    def __reset_filter(self, view):
        """
        重置条件
        """
        if view == "parking":
            filter_name = "ParkingFilter"
        elif view == "entrance":
            filter_name= "EntranceFilter"
        elif view == "exit":
            filter_name= "ExitFilter"
        elif view == "past":
            filter_name= "PastFilter"
        filters = session.get(filter_name)
        if filters:
            del session[filter_name]
        return "OK"

    def __set_filter(self, view, **data):
        """
        设置条件
        """
        if view == "parking":
            session['ParkingFilter'] = data
        elif view == "entrance":
            session['EntranceFilter'] = data
        elif view == "exit":
            session['ExitFilter'] = data
        elif view == "past":
            session['PastFilter'] = data
        return "OK"

    def __delete_data(self, view, **data):
        """
        删除数据
        """
        data_name = self.__view_names.get(view)
        if data_name:
            if view in ("parking","past"):
                ret = RecordParking.delete_data(**data)
        if ret:
            return self.success(f"{data_name}刪除成功")
        return self.warning(f"{data_name}刪除失敗")

    def post_data_handler(self, **kwargs):
        """
        POST数据处理
        """
        view = kwargs.get("View")
        for k, v in kwargs.items():
            if k == "Delete":
                return self.__delete_data(view, **v)
            elif k == "SetFilter":
                return self.__set_filter(view, **v)
            elif k == "ResetFilter":
                return self.__reset_filter(view)
            elif k == "GetData":
                return self.__get_data(view, **v)
        return self.error("請求錯誤，請聯係管理員")
        
    def __generate_page_data(self, *args):
        """
        生成页面数据
        """
        return {
            "ColumnName":args[0], 
            "ColumnNameJSON": json.dumps(args[0],ensure_ascii=False), 
            "TableDatas": args[1],
            "Filters": args[2],
            "FiltersJSON": json.dumps(args[2],ensure_ascii=False),
        }

    def ____form_page_data(self, *args):
        """
        表单页面数据
        """
        return {
            "ColumnName":args[0], 
            "ColumnNameJSON": json.dumps(args[0],ensure_ascii=False), 
            "SettingFormData": json.dumps(args[1],ensure_ascii=False)
        }

    def charge_page_data(self):
        """
        收费记录
        """
        filters = session.get("ChargeFilter")
        if not filters:
            filters = {"ChargeTime": ""}
        # data_filters = RecordParking.generate_filters(**filters)
        table_datas = ChargeDetail.query.filter_by(Deleted=True).all()
        column_name = ChargeDetail.column_name()
        return self.__generate_page_data(*[column_name, table_datas, filters])

    def parking_page_data(self):
        """
        在场记录
        """
        filters = session.get("ParkingFilter")
        if not filters:
            filters = {"EntranceTime": ""}
        # data_filters = RecordParking.generate_filters(**filters)
        table_datas = RecordParking.query.filter_by(Deleted=True,ExitTime=None).all()
        column_name = RecordParking.columns_name()
        return self.__generate_page_data(*[column_name, table_datas, filters])

